package com.ekuaitu.kuaitustaff.api;

import com.ekuaitu.kuaitustaff.BuildConfig;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class ParseApiStore {
    private static ParseApiStore instance = null;
    private static Retrofit retrofit;

    private ParseApiStore() {
    }

    public static ParseApiStore getInstance() {
        if (instance == null) {
            synchronized (ParseApiStore.class) {
                if (instance == null) {
                    instance = new ParseApiStore();
                }
            }
        }
        return instance;
    }

    public ApiService getApiService(String baseUrl) {
        return getRetrofit(baseUrl).create(ApiService.class);
    }

    public Retrofit getRetrofit(String baseUrl) {
        //配置okHttp
        OkHttpClient.Builder builder = new OkHttpClient
                .Builder()
                .readTimeout(120, TimeUnit.SECONDS);
        builder.addInterceptor(chain -> {
            Request original = chain.request();
            Request request = original.newBuilder()
                    .header("X-Parse-Application-Id", "e8b9ed3e57a3c04c56b4ec7bd82d3b47")
                    .header("X-Parse-REST-API-Key", "4c56b4ec7bd82d3b47e8b9ed3e57a3c0")
                    .header("Content-Type", "application/json")
                    .build();
            return chain.proceed(request);
        });
        if (BuildConfig.DEBUG) {
            //debug模式
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Logger.i("OkHttpClient", "OkHttpMessageParse:" + message);
                }
            });
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
            builder.addInterceptor(MyApplication.chuckInterceptor);
        }
        //配置Retrofit
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(getGson()))
                .build();

        return retrofit;
    }

    /**
     * java bean 转化json数据  序列化
     * 解析反序列化
     *
     * @return
     */
    public Gson getGson() {
        return new GsonBuilder()
                .serializeNulls()//允许序列化反序列化为null
                .create();
    }
}
